package com.zys.asseter.service;

import com.zys.asseter.domain.pojo.FileEntity;
import com.zys.asseter.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileService {

    @Autowired
    private FileMapper fileMapper;

    private final Path rootLocation = Paths.get("uploads");

    public void store(MultipartFile file, String type) throws IOException {
        // Ensure the upload directory exists
        Files.createDirectories(rootLocation);

        // Save the file to the filesystem
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, this.rootLocation.resolve(file.getOriginalFilename()));
        }

        // Create a FileEntity object with metadata
        FileEntity fileEntity = new FileEntity();
        fileEntity.setFileName(file.getOriginalFilename());
        fileEntity.setFilePath(this.rootLocation.resolve(file.getOriginalFilename()).toString());
        fileEntity.setFileType(file.getContentType());
        fileEntity.setFileSize(file.getSize());

        // Insert into database
        fileMapper.insertFile(fileEntity);
    }
}
